package com.bdqn.dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Properties;

import com.bdqn.entity.PetOwner;

public class BaseDao {
	private static String driver;
	private static String url;
	private static String user;
	private static String password;
	
	static{
		 try {
			init();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private static void init() throws IOException{
		Properties params=new Properties();
		String configFile = "bdqn.properties";
		InputStream is = BaseDao.class.getClassLoader().getResourceAsStream(configFile);
		params.load(is);
		driver=params.getProperty("driver");
		url=params.getProperty("url");
		user=params.getProperty("user");
		password=params.getProperty("password");
	}
	public static Connection getConnection() throws Exception {
		Class.forName(driver);
		Connection connection = DriverManager.getConnection(url,user,password);
		return connection;
	}
	public void claseAll(Connection connection,Statement stmt,ResultSet result)throws
	SQLException{
		if (result !=null) {
			result.close();
		}
		if (stmt !=null) {
			stmt.close();
		}
		if (connection !=null) {
			connection.close();
		}
		
	}
	public int exceuteInsert(String preparedSql, List<Object> param) throws Exception {
		Connection conn = getConnection();
		PreparedStatement pstmt = conn.prepareStatement(preparedSql, Statement.RETURN_GENERATED_KEYS);
		
		for (int i = 0; i < param.size(); i++) {
			pstmt.setObject(i+1, param.get(i));
		}
		
		int rows = pstmt.executeUpdate();
		ResultSet result =  pstmt.getGeneratedKeys();
		if (result.next()) {
			rows = result.getInt(1);
		}
		claseAll(conn,pstmt,result);
	
		return  rows;
	}

	public int exceuteUpdate(String preparedSql, List<Object> param)throws Exception {
		Connection conn = getConnection();
		PreparedStatement pstmt = conn.prepareStatement(preparedSql);
		for (int i = 1; i <= param.size(); i++) {
			pstmt.setObject(i, param.get(i-1));
		}
		int rows = pstmt.executeUpdate();
		return rows;
		 
	}


}
